<template>
  <AppPage :show-footer="true">
    <div flex>
      <!-- 挂号 -->
      <n-card title="新增挂号" size="small" w-350 :segmented="true" mt-15 rounded-10>
        <template #header-extra>
          <n-button text type="primary">更多</n-button>
        </template>
        <div flex flex-wrap justify-between>
          <n-form ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto" require-mark-placement="right-hanging" :size="size" :style="{
              maxWidth: '300px',
              minWidth: '210px'
            }">
            <n-form-item label="预约时间" path="inputValue">
              <n-date-picker type="datetime" v-model:value="model.time_registration" :default-value="Date.now()" :is-date-disabled="dateDisabled" :is-time-disabled="timeDisabled" />
            </n-form-item>
            <n-form-item label="姓名" path="name_patient">
              <n-input v-model:value="model.name_patient" placeholder="请输入 姓名" />
            </n-form-item>
            <n-form-item label="手机号码" path="phone_patient">
              <n-input v-model:value="model.phone_patient" placeholder="请输入 手机号码" />
            </n-form-item>

            <n-form-item label="出生日期" path="birth_patient">
              <n-date-picker v-model:value="model.birth_patient" type="date" />
            </n-form-item>

            <n-form-item label="年龄" path="age_patient">
              <n-input v-model:value="model.age_patient" placeholder="请输入 年龄" />
            </n-form-item>

            <n-form-item label="身份证" path="identity_patient">
              <n-input v-model:value="model.identity_patient" placeholder="请输入 身份证 " />
            </n-form-item>

            <n-form-item label="性别" path="sex_patient">
              <n-radio-group v-model:value="model.sex_patient" name="sex_patient">
                <n-space>
                  <n-radio value="1">
                    男
                  </n-radio>
                  <n-radio value="2">
                    女
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>

            <div style="display: flex; justify-content: center">
              <n-button type="info" @click="submitForm">
                提交预约
              </n-button>
            </div>
          </n-form>
        </div>
      </n-card>
      <div class="ml-10 mt-15">
        <n-card class="w-700 flex-shrink-0  mb-10 cursor-pointer" rounded-10 hover:card-shadow title="预约时间" size="small">
          <n-date-picker type="datetime" v-model:value="model.time_registration" :default-value="Date.now()" :is-date-disabled="dateDisabled" :is-time-disabled="timeDisabled" />
        </n-card>
        <n-card class="w-700 flex-shrink-0  mb-10 cursor-pointer" rounded-10 hover:card-shadow size="small">
          <n-data-table :columns="columns" :data="state.data" :pagination="table.pagination" :bordered="false" />
        </n-card>
      </div>
    </div>
  </AppPage>
</template>
<script setup>
import { useUserStore } from '@/store'
import { NButton, useMessage, NText } from "naive-ui";
import { reactive } from 'vue';
import api from './api'

const userStore = useUserStore()
// 表单
const formRef = ref(null);
const message = useMessage();
// 大小
const size = ref("large");
// 数据
const model = ref({
  // 病人信息
  name_patient: null,//姓名
  phone_patient: null,//手机
  birth_patient: null,//生日
  age_patient: null,//年龄
  identity_patient: null,//身份证
  sex_patient: null,//性别
  // 预约时间
  time_registration: null
});
// 列表对象展示
const columns = ref([
  {
    title: "挂号ID",
    key: "id_registration"
  },
  {
    title: "患者姓名",
    key: "patient.name_patient"
  },
  {
    title: "电话",
    key: `patient.phone_patient`
  },
  {
    title: "患者身份证号",
    key: `patient.identity_patient`
  },

  {
    title: "状态",
    key: `state_registration`,
    render (row) {
      if (row.state_registration == "1") {
        return h(
          NText, { depth: 1 },
          { default: () => '已就诊' }
        )
      } else {
        return h(
          NText, { depth: 1 },
          { default: () => '未就诊' }
        )
      }
    }
  }
]);
const table = reactive({
  pagination: {
    pageSize: 5,
  },
})

// 列表数据
const state = reactive({
  data: []
});
// 预约时间  限定
const dateDisabled = (ts) => {
  return ts <= Date.now() - 1 * 24 * 3600 * 1000
}
const timeDisabled = (ts) => {
  const date = new Date(ts).getDate();
  return {
    isHourDisabled: (hour) => {
      return hour < date;
    }
  };
}
// 表单校验规则
const rules = reactive({
  name_patient: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入 姓名"
  },
  phone_patient: {
    required: true,
    trigger: ["input"],
    validator: (rule, value) => {
      return /\d{3}-\d{8}|\d{4}-\d{7}|^1(3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\d{8}$/.test(value);
    }
  },
  birth_patient: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入 出生日期'
  },
  // 身份证校验
  identity_patient: {
    required: true,
    trigger: ["input"],
    validator: (rule, value) => {
      return /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value);
    }
  },
  sex_patient: {
    required: true,
    trigger: 'change',
    message: '请选择 性别'

  },
  time_registration: {
    type: 'datetime',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入 预约时间'
  }
})
// 添加挂号信息，且创建患者信息   提交表单
const submitForm = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 业务
      api.addRegistration({ data: model.value }).then((res) => {
        console.log(res, "resresres");
        if (res.data) {
          message.success("预约成功")
          getData()
        } else {
          message.error("预约错误")
        }
      })
    } else {
      console.log(errors);
      message.error("信息填写错误");
    }
  });
}

async function getData () {
  const { data } = await api.findAllRegistration()
  state.data = data
}
//初始挂载
onMounted(() => {
  getData()
})
</script>
